package com.cnb.telepathytalk.util;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.cnb.telepathytalk.dto.NoticeDTO;

public class NoticeParser {
	private static final String TAG = "NoticeParser";
	private static final String XML_URL = "http://telepathy.cnbridge.co.kr/xml/noticeList.cnb?type=android";

	public ArrayList<NoticeDTO> parsingData() {
		ArrayList<NoticeDTO> list = new ArrayList<NoticeDTO>();

		try {
			XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();

			HttpClient client = new DefaultHttpClient();

			client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost post = new HttpPost(XML_URL);

			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if (response.getStatusLine().getStatusCode() != 200) {
				Log.e(TAG, "POST ERROR!!!");
			}

			parser.setInput(entity.getContent(), "UTF-8");

			NoticeDTO item = null;
			String tag = "";
			int event = parser.next();

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					tag = parser.getName();
					if ("item".equals(tag)) {
						item = new NoticeDTO();
					} else if ("result".equals(tag)) {
						item.setResult(parser.nextText().equals("true"));
					} else if ("NUM".equals(tag)) {
						item.setNum(parser.nextText());
					} else if ("TITLE".equals(tag)) {
						item.setTitle(parser.nextText());
					} else if ("WRITER".equals(tag)) {
						item.setWriter(parser.nextText());
					} else if ("CONTENT".equals(tag)) {
						item.setContent(parser.nextText());
					} else if ("REG_DATE".equals(tag)) {
						item.setDate(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					tag = parser.getName();
					if ("item".equals(tag)) {
						list.add(item);
					}
					break;
				default:
					break;
				}
				event = parser.next();
			}

		} catch (Exception e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
		}

		return list;
	}
}